import { Component, Input, ChangeDetectionStrategy, NgZone, ChangeDetectorRef } from '@angular/core';
import { getTimeDistance } from '@delon/util';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';
import { format } from 'date-fns';

/**
 * 维修数据合计组件
 */
@Component({
  selector: 'prod-repair-summary',
  templateUrl: './repair-month-sum.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RepairMonthSumComponent {
  _codeName = null;
  @Input()
  set codeName(val) {
    if (val) {
      this._codeName = val;
      this.attachData(this._codeName);
    }
  }
  loading = false;
  i = { start: null, end: null };
  total = 0;
  data = [];
  time = null;
  info = '';
  now = 0;
  last = 0;
  month = 0;

  constructor(
    public http: _HttpClient,
    public msg: NzMessageService,
    private ngZone: NgZone,
    private cdr: ChangeDetectorRef,
  ) {}

  private attachData(codeName) {
    const { ngZone } = this;
    ngZone.run(() => {
      this.total = 0;
      this.data = [];
      this.loading = true;
      this.cdr.detectChanges();
    });
    // const endDate = format(this.i.end, 'YYYY-MM-DD');
    // const startDate = format(this.i.start, 'YYYY-MM-DD');
    this.http.get(`/cf/report/prod/repairsummary/${codeName}`).subscribe(res => {
      ngZone.run(() => {
        this.time = new Date();
        this.total = res.data.sum;
        this.now = res.data.now;
        this.last = res.data.last;
        this.month = res.data.month;
        this.data = res.data.list.map(r => {
          return { x: r.MONTH, y: r.COUNT };
        });
        this.loading = false;
        this.cdr.detectChanges();
      });
    });
  }

  calcTb() {
    const { now, last } = this;
    if (last === 0) {
      return '-';
    }
    // tslint:disable-next-line: radix
    return parseInt(Math.abs(((now - last) / last) * 100) + '') + '%';
  }
}
